# models/user.py
"""
用户相关的数据模型
- User: 用户基本信息表，存储用户的基本信息
"""

import enum
import uuid
from datetime import datetime, UTC
from sqlalchemy import Column, Integer, String, DateTime, Enum, text
from sqlalchemy.orm import relationship

from dao.postgresql_connect import Base

class UserRole(enum.Enum):
    """用户角色枚举"""
    USER = "user"
    ADMIN = "admin"

class UserStatus(enum.Enum):
    """用户状态枚举"""
    ACTIVE = "active"
    INACTIVE = "inactive"

class User(Base):
    """用户基本信息表"""
    __tablename__ = 'users'

    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()), index=True)
    username = Column(String, index=True)
    password = Column(String(255))  # 添加密码字段
    # 限制手机号区号为3位，手机号为11位
    country_code = Column(String(3), default='+86')  # 默认中国区号
    phone = Column(String(11), unique=True, index=True)
    # 设置 email 字段长度为 254，允许为空
    email = Column(String(254), unique=True, index=True, nullable=True)
    # 用户头像，存储 base64 格式的图片数据
    avatar = Column(String, nullable=True)
    role = Column(Enum(UserRole), default=UserRole.USER, nullable=False, comment='用户角色')
    status = Column(Enum(UserStatus), default=UserStatus.ACTIVE, nullable=False, comment='账号状态')
    last_login_at = Column(DateTime, comment='最后登录时间')
    created_at = Column(DateTime, default=lambda: datetime.now(UTC), nullable=False, comment='创建时间')
    updated_at = Column(DateTime, default=lambda: datetime.now(UTC), server_default=text('CURRENT_TIMESTAMP'), nullable=False, comment='更新时间')

    # 关系
    created_apps = relationship('App', back_populates='creator')
    installed_apps = relationship('UserInstalledApp', back_populates='user')
    chat_sessions = relationship('ChatSession', back_populates='user')
    quotas = relationship('UserQuota', back_populates='user')
